package com.imooc.springcloud;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

/**
 * @describte:TODO
 * @program:spring-cloud
 * @author:zhengdp
 * @create:2021-09-28 18:01:02
 **/
@Service
@Slf4j
@Deprecated
public class AccessLimiter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisScript<Boolean> rateLimitLua;

    /**
     * 限流
     * @param key 要进行限流的方法标识
     * @param limit 每秒钟的限制请求
     */
    public void limitAccess(String key,Integer limit){
        // step1 : request lua script
        boolean acquired = stringRedisTemplate.execute(rateLimitLua,
                Lists.newArrayList(key), // Lua脚本中的key列表
                limit.toString() // Lua脚本Value列表
                );

        if(!acquired){
            log.error("your access is blocked, key = {}",key);
            throw new RuntimeException("Your access is blocked");
        }
    }
}
